// client/components/Recommendations.js
import React, { useState, useEffect, useContext } from "react";
import getConfig from "next/config";
import Link from "next/link";
import { useRouter } from "next/router";
import Box from "./Box";
import Text from "./Text";
import TorrentList from "./TorrentList";
import LoadingContext from "../utils/LoadingContext";
import { NotificationContext } from "./Notifications";
import LocaleContext from "../utils/LocaleContext";

const Recommendations = ({ token, count = 6 }) => {
  const [recommendations, setRecommendations] = useState([]);
  const [torrents, setTorrents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [needsOnboarding, setNeedsOnboarding] = useState(false);

  const { setLoading: setGlobalLoading } = useContext(LoadingContext);
  const { addNotification } = useContext(NotificationContext);
  const { getLocaleString } = useContext(LocaleContext);

  const router = useRouter();

  const {
    publicRuntimeConfig: { SQ_API_URL, SQ_TORRENT_CATEGORIES },
  } = getConfig();

  useEffect(() => {
    const fetchRecommendations = async () => {
      if (!token) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);

        const response = await fetch(
          `${SQ_API_URL}/recommendation/recommendations?count=${count}`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );

        console.log("获取推荐:", response);
        if (!response.ok) {
          throw new Error(`获取推荐失败: ${response.status}`);
        }

        const data = await response.json();
        console.log("获取推荐:", data);

        // Check if recommendations exist and are not empty
        if (!data.recommendations || data.recommendations.length === 0) {
          // For now, we'll assume empty recommendations means onboarding is needed
          // You may need to customize this logic based on your actual API behavior
          setNeedsOnboarding(true);
          setLoading(false);
        } else {
          // Store recommendations in state
          setRecommendations(data.recommendations);

          // Fetch the full torrent details for each recommended torrentId
          await fetchTorrentDetails(data.recommendations);
        }
      } catch (error) {
        console.error("获取推荐失败:", error);
        addNotification(
          "error",
          getLocaleString("recommendations.error") || "获取推荐失败"
        );
        setLoading(false);
      }
    };

    // Function to fetch torrent details for each recommendation
    const fetchTorrentDetails = async (recommendations) => {
      if (!recommendations || recommendations.length === 0) {
        setLoading(false);
        return;
      }

      try {
        // 创建数组存储所有种子数据
        const torrentsData = [];
        let errorCount = 0;

        // 使用推荐 API 返回的 ID 获取种子详情
        for (const rec of recommendations) {
          try {
            // 获取推荐 ID
            const torrentId = rec.torrentId;

            // 修改为使用 /torrent/details/:id 接口 (需要在后端增加此接口)
            const response = await fetch(
              `${SQ_API_URL}/torrent/details/${torrentId}`,
              {
                headers: {
                  Authorization: `Bearer ${token}`,
                },
              }
            );

            if (response.ok) {
              const torrentData = await response.json();

              // 获取评论数据
              // 注意：使用与 TorrentList 相同的评论数计算方式，确保评论数的一致性
              let commentCount = 0;
              if (torrentData.comments && Array.isArray(torrentData.comments)) {
                commentCount = torrentData.comments.length;
              } else if (
                torrentData.comments &&
                torrentData.comments.count !== undefined
              ) {
                commentCount = torrentData.comments.count;
              }

              // 处理三维评分数据
              // 完全匹配 TorrentList 组件中的评分处理逻辑
              let scoreValue = 0;
              let scoreStats = {};

              // 首先尝试使用已有的 scoreStats
              if (torrentData.scoreStats) {
                scoreStats = torrentData.scoreStats;
                scoreValue = scoreStats.overallScore || 0;
              }
              // 如果没有 scoreStats 但有 score
              else if (torrentData.score) {
                scoreValue = torrentData.score;
                // 构建与 TorrentList 组件中相同的 scoreStats 结构
                scoreStats = {
                  overallScore: scoreValue,
                  technicalScore: 0, // 默认值
                  contentScore: scoreValue * 20, // 将5分制转换为100分制
                  communityScore: 0, // 默认值
                  reliability: torrentData.ratingCount
                    ? Math.min(torrentData.ratingCount / 20, 1)
                    : 0,
                };
              }

              // 确保有评分更新时间
              // 如果没有 lastUpdated，则使用当前时间
              if (!scoreStats.lastUpdated) {
                scoreStats.lastUpdated = new Date();
              }

              // 增强种子对象，添加推荐信息和三维评分数据
              const enhancedTorrent = {
                ...torrentData,
                recommendationScore: rec.score,
                recommendationReason: rec.reason,
                algorithm: rec.algorithm,
                // 确保评分数据结构与 TorrentList 期望的一致
                score: scoreValue,
                scoreStats: scoreStats,
                comments: {
                  count: commentCount,
                },
              };

              torrentsData.push(enhancedTorrent);
            } else {
              console.warn(`获取种子失败 ${torrentId}: ${response.status}`);
              errorCount++;
            }
          } catch (err) {
            console.warn(`获取种子出错 ${rec.torrentId}:`, err);
            errorCount++;
          }
        }

        // 更新种子状态
        setTorrents(torrentsData);

        // 显示错误通知
        if (errorCount > 0 && errorCount < recommendations.length) {
          addNotification(
            "warning",
            getLocaleString("recommendations.partialError") ||
              `${errorCount} 个推荐内容加载失败`
          );
        } else if (errorCount === recommendations.length) {
          addNotification(
            "error",
            getLocaleString("recommendations.allError") ||
              "所有推荐内容加载失败"
          );
        }
      } catch (error) {
        console.error("获取种子详情失败:", error);
        addNotification(
          "error",
          getLocaleString("torrents.fetchError") || "获取种子详情失败"
        );
      } finally {
        setLoading(false);
      }
    };

    fetchRecommendations();
  }, [token, count]);

  const handleGoToPreferences = () => {
    setGlobalLoading(true);
    router.push("/preferences");
  };

  if (loading) {
    return (
      <Box mb={5}>
        <Text as="h2" mb={4}>
          {getLocaleString("recommendations.forYou") || "为您推荐"}
        </Text>
        <Text>{getLocaleString("common.loading") || "加载中..."}</Text>
      </Box>
    );
  }

  if (needsOnboarding) {
    return (
      <Box mb={5}>
        <Text as="h2" mb={4}>
          {getLocaleString("recommendations.forYou") || "为您推荐"}
        </Text>
        <Box
          bg="sidebar"
          p={4}
          borderRadius={1}
          border="1px solid"
          borderColor="border"
        >
          <Text mb={3}>
            {getLocaleString("recommendations.completePreferences") ||
              "完善偏好设置以获取个性化推荐"}
          </Text>
          <Box
            as="button"
            onClick={handleGoToPreferences}
            bg="primary"
            color="white"
            py={2}
            px={3}
            borderRadius={1}
            border="none"
            cursor="pointer"
          >
            {getLocaleString("recommendations.setPreferences") || "设置偏好"}
          </Box>
        </Box>
      </Box>
    );
  }

  if (!torrents.length) {
    return (
      <Box mb={5}>
        <Text as="h2" mb={4}>
          {getLocaleString("recommendations.forYou") || "为您推荐"}
        </Text>
        <Text>{getLocaleString("recommendations.none") || "暂无推荐内容"}</Text>
      </Box>
    );
  }

  return (
    <Box mb={5}>
      <Box
        display="flex"
        justifyContent="space-between"
        alignItems="center"
        mb={4}
      >
        <Text as="h2">
          {getLocaleString("recommendations.forYou") || "为您推荐"}
        </Text>
        <Link href="/preferences" passHref>
          <Text as="a" color="primary" fontSize={1}>
            {getLocaleString("recommendations.preferences") || "偏好设置"}
          </Text>
        </Link>
      </Box>
      <TorrentList
        torrents={torrents}
        categories={SQ_TORRENT_CATEGORIES}
        showRecommendationReason={true}
      />
    </Box>
  );
};

export default Recommendations;
